/**
 * Copyright (C) 2010 D. Zoller, M. Richter, M. Blumenstein & W. Biller
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.siafu.rest.providers.exceptionmappers;

import java.net.SocketTimeoutException;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.siafu.rest.exceptions.InternalServerException;


/**
 * maps a internal server exception to serverError response (500)
 * if the siafu tcp server is not reachable or not ready to execute external commands
 * this mapper renders a SERVICE_UNAVAILABLE response
 * 
 * @author D. Zoller
 * @version $Id: InternalServerExceptionMapper.java,v 1.4 2010-06-14 07:57:57 nosebrain Exp $
 */
@Provider
public class InternalServerExceptionMapper implements ExceptionMapper<InternalServerException> {
	
	private static final Log log = LogFactory.getLog(InternalServerExceptionMapper.class);
	
	public Response toResponse(InternalServerException exception) {
		if (exception.getCause() != null && (exception.getCause().getClass().isAssignableFrom(SocketTimeoutException.class))) {
			log.debug("siafu server not started?!?");
			return Response.status(Status.SERVICE_UNAVAILABLE).build();
		}
		
		log.fatal("error", exception);
		return Response.serverError().build();
	}

}
